package top.continew.minithreadpool.concurrent;
import top.continew.minithreadpool.concurrent.ThreadPool;
import top.continew.minithreadpool.factory.ThreadFactory;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 工作线程类
 */
public class Worker extends ReentrantLock implements Runnable {
    final Thread thread;
    Runnable firstTask;
    volatile long completedTasks;
    volatile boolean completedAbruptly;
    private final ThreadPool threadPool;

    public Worker(ThreadPool threadPool, Runnable firstTask, ThreadFactory threadFactory) {
        this.threadPool = threadPool;
        this.firstTask = firstTask;
        this.thread = threadFactory.newThread(this);
        this.completedAbruptly = false;
    }

    @Override
    public void run() {
        threadPool.runWorker(this);
    }

    public void interruptIfStarted() {
        if (thread != null && !thread.isInterrupted()) {
            try {
                thread.interrupt();
            } catch (SecurityException ignore) {
            }
        }
    }
}
